package com.huawei.cloud.phone.management.infrastructure.user;

import com.huawei.cloud.phone.management.domain.user.User;
import com.huawei.cloud.phone.management.domain.user.UserGateway;
import com.huawei.cloud.phone.management.infrastructure.db.mapper.UserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Slf4j
@AllArgsConstructor
@Component
public class UserGatewayImpl implements UserGateway {
    private final UserMapper userMapper;

    @Override
    public Optional<User> saveUser(User user) {
        try {
            if(userMapper.saveUser(user) == 0) {
                return Optional.empty();
            }
        } catch (DuplicateKeyException e) {
            log.error("save user failed.", e);
            return Optional.empty();
        }
        return getUser(user.getUsername(), user.getPassword());
    }

    @Override
    public Optional<User> getUser(String username, String password) {
        return Optional.ofNullable(userMapper.getUser(username, password));
    }

    @Override
    public Optional<String> getUserId(String username) {
        return Optional.ofNullable(userMapper.getUserId(username));
    }
}
